﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace CakemailIntegration
{
    /// <summary>
    /// Summary description for RestRegisterProvider
    /// </summary>
    public class RestRegisterProvider : IHttpHandler
    {
        private string _apiKey = string.Empty; //take from config
        private string user_key = string.Empty; //take from config

        public void ProcessRequest(HttpContext context)
        {
            var req = WebRequest.Create("https://api.wbsrvc.com/List/subscribeEmail/");
            req.Method = "POST";
            var encoding = new ASCIIEncoding();

            if (string.IsNullOrWhiteSpace(context.Request.QueryString["list_id"]))
            {
                context.Response.StatusCode = 400;
                req.ContentType = "text/plain";
                context.Response.Flush();
                return;
            }

            var queryToSend = string.Format("user_key={0}&{1}",user_key,context.Request.Url.Query.Replace("?",""));

            //send initial subscription
            var data = queryToSend;
            byte[] byte1 = encoding.GetBytes(data);

            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = byte1.Length;
            req.Headers.Add("apikey", _apiKey);
            var newStream = req.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            newStream.Close();

            context.Response.StatusCode = 200;
            //context.Response.Status = "Request Successful";
            req.ContentType = "text/plain";
            context.Response.Flush();

            return;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}